package com.yesep.learn.jwt.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.yesep.learn.jwt.common.R;
import com.yesep.learn.jwt.exception.LoginFailLimitException;
import com.yesep.learn.jwt.util.ServletUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 用户登录系统失败后 需要做的业务操作 当用户登录系统失败后则会进入到此类并执行相关业务
 */
@Slf4j
public class AuthenticationFailureHandlerImpl extends SimpleUrlAuthenticationFailureHandler {
	@Override
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
		// String username = request.getParameter("username");
		Integer status = 106;
		String message = "验证错误";
		if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException || e instanceof InternalAuthenticationServiceException) {
			status = 101;
			message = "账号或密码错误";
		} else if (e instanceof DisabledException) {
			status = 102;
			message = "账号被禁用";
		} else if (e instanceof AccountExpiredException || e instanceof CredentialsExpiredException) {// 账号是否未过期、账号凭证是否未过期
			status = 103;
			message = "账号已失效";
		} else if (e instanceof LockedException) {// 账号是否未锁定
			status = 104;
			message = "账号被锁定";
		} else if (e instanceof LoginFailLimitException) {// 连续多次错误登录异常
			status = 105;
			message = "连续错误次数 " + ((LoginFailLimitException) e).getErrors();
		}
		response.setStatus(HttpServletResponse.SC_FORBIDDEN);
		ServletUtils.writeValueAsString(R.me(HttpServletResponse.SC_FORBIDDEN, message), response);
	}
}
